<template>
  <el-dialog :title="title" v-model="visible" width="400">
    <slot>
      <div class="p-16" v-loading="loading">
        <img v-if="loginEQ" :src="loginEQ" class="w-48 h-48" style="margin: 0 auto" />
      </div>
      <!-- 渲染纯js窗体 -->
      <div v-html="contentBody" v-if="contentBody"></div>
    </slot>
    <!-- <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel" :disabled="confirmLoading"> {{ cancelText }}</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="$emit('confirm')">{{ confirmText }}</el-button>
      </span>
    </template> -->
  </el-dialog>
</template>

<script setup>
import { computed, defineProps, defineEmits, ref } from 'vue';
// 纯js调用时必须，不然解析不出<el-dialog></el-dialog>、<el-button />
import { loginpclog_list } from '@/api/index.js';
import { ElDialog, ElButton } from 'element-plus';
import axios from 'axios';
import SnowflakeId from 'snowflake-id';
const snowflake = new SnowflakeId();
const intervalId = ref(null);
const props = defineProps({
  modelValue: false,
  title: '',
  cancelText: {
    type: String,
    default: '取消',
  },
  confirmText: {
    type: String,
    default: '确定',
  },
  loading: false,
  contentBody: null,
});
const loginEQ = ref('');
const emits = defineEmits(['update:modelValue', 'cancel', 'close']);
// 纯js实例调用改变loading属性
const _loading = ref(false);
const loading = ref(true);
const confirmLoading = computed(() => {
  return props.loading || _loading.value;
});

const visible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emits('update:modelValue', val);
  },
});
async function wxloginopen() {
  console.log('wxloginopen:');
  let id = snowflake.generate();
  const instance = axios.create({
    baseURL: '/weixin',
    // 指定请求超时的毫秒数
    timeout: 10000,
    // 表示跨域请求时是否需要使用凭证
    withCredentials: false,
  });
  await instance({
    method: 'get',
    url: '/cgi-bin/token?grant_type=client_credential&appid=wxfb02cc61a6ef3971&secret=fabd1914b14d949a04b1041883a4ee3b',
  }).then(async (res) => {
    console.log('wxloginopen=》res:', res);
    await instance({
      method: 'post',
      url: `/wxa/getwxacodeunlimit?access_token=${res.data.access_token}`,
      data: {
        scene: id,

        page: 'pages/userinfo/pclogin', // 这里按照需求设置值和参数
      },
      responseType: 'arraybuffer',
    }).then((res2) => {
      console.log('res2', res2);
      const arrayBuffer = res2.data;
      return new Promise((resolve, reject) => {
        // 创建一个Blob对象
        const blob = new Blob([arrayBuffer], { type: 'application/octet-stream' });

        // 创建一个FileReader对象
        const reader = new FileReader();

        // 定义FileReader的onload事件处理函数
        reader.onload = function (event) {
          // 将ArrayBuffer转换为Base64编码的字符串
          const base64String = event.target.result;
          resolve(base64String);
        };

        // 定义FileReader的onerror事件处理函数
        reader.onerror = function (error) {
          reject(error);
        };

        // 将Blob转换为Data URL并触发onload事件
        reader.readAsDataURL(blob);
      }).then((base64String) => {
        console.log('base64String', base64String);
        loginEQ.value = base64String;
        loading.value = false;
        console.log('loginEQ', loginEQ.value);

        // 设置3分钟等于180000毫秒
        const threeMinutes = 3 * 60 * 1000;

        intervalId.value = setInterval(function () {
          loginjg(id);
        }, 1000); // 每1000毫秒（即每秒）调用一次 loginjg 方法

        // 使用 setTimeout 来停止 setInterval
        setTimeout(function () {
          clearInterval(intervalId);
        }, threeMinutes);
      });
    });
  });
}
wxloginopen();
function stopTimer() {
  if (intervalId.value) {
    clearInterval(intervalId.value);
    console.log('计时器已停止');
  }
}
function loginjg(code) {
  loginpclog_list({ pcCode: code }).then((res) => {
    if (res.data.code === 200 && res.data.data.userinfo) {
      // userinfo.value = res.data.data.userinfo;
      localStorage.setItem('userinfo', JSON.stringify(res.data.data.userinfo));
      localStorage.setItem('vipinfo', JSON.stringify(res.data.data.vipinfo));
      stopTimer();
      visible.value = false;
      window.location.reload();
    }
  });
}
// methods
const handleCancel = () => {
  emits('cancel');
  visible.value = false;
};

const showLoading = () => {
  _loading.value = true;
};

const hideLoading = () => {
  _loading.value = false;
};
// 暴露给纯js实例调用，可在实例中使用instance._instance.exposed查询到
defineExpose({ showLoading, hideLoading });
</script>

